<?php

namespace App\Models;


use App\Models\Traits\HasModelLog;
use App\Models\Traits\Observe;
use DateTimeInterface;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

//基础model

/**
 * App\Models\BaseModel
 *
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel filter(array $input = [], $filter = null)
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel paginateFilter($perPage = null, $columns = [], $pageName = 'page', $page = null)
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel simplePaginateFilter($perPage = null, $columns = [], $pageName = 'page', $page = null)
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel whereBeginsWith($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel whereEndsWith($column, $value, $boolean = 'and')
 * @method static \Illuminate\Database\Eloquent\Builder|BaseModel whereLike($column, $value, $boolean = 'and')
 * @mixin \Eloquent
 */
class BaseModel extends Model
{
    use HasModelLog, Filterable, Observe;

    protected static $data = null;
    protected static $asname = "name";

    /** @var \Illuminate\Database\Eloquent\Builder */
    protected $queryModel;
    const PAGE_SIZE = 20;
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];

    /** @var array */
    protected $sources;
    protected $guarded = ['id'];

    public function setSources($data)
    {
        $this->sources = collect($data)->toArray();
    }

    public function getSources()
    {
        return $this->sources;
    }


    function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        //自动分表
//        if (method_exists($this, 'subTable')) {
//            $this->subTable();
//        }
    }

    /**
     * 设置过滤数据库没有的字段
     * @param $key
     * @param string $value
     */
    public function setValue($key, $value = "")
    {
        if (empty($this->fillable)) {
            $this->fillable = $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
        }
        if (is_array($key)) {
            $result = array_intersect_key($key, array_flip($this->fillable));
            $this->fill($result);
        } else {
            if (in_array($key, $this->fillable)) {
                $this->$key = $value;
            }
        }
        return $this;
    }

    /** 实例化一个和model绑定的查询构建器 */
    public function getQueryByModel($new = false)
    {
        if ($new || empty($this->queryModel)) {
            $this->queryModel = $this->newQuery();
        }
        return $this->queryModel;
    }


    public function save(array $options = [])
    {
        return parent::save($options); // TODO: Change the autogenerated stub
    }

    /**
     * grid列表查询
     * @param array $params
     * @return array
     */
    public function apigrid($params = [])
    {
        $pageSize = empty($params['limit']) ? self::PAGE_SIZE : intval($params['limit']);
        $query = $this->getQueryByModel();
        if (isset($params['sort'])) {
            $query->orderBy(trim($params['sort']), trim(Arr::get($params, 'order', 'asc')));
        } else {
            $query->orderBy($this->getKeyName(), 'desc');
        }
        return !empty($pageSize) ? $query->apiPaginate($pageSize) : $query->get();
    }

    /**
     * 获取所有记录
     * @param array $where
     * @param array $field
     * @return \Illuminate\Database\Eloquent\Collection|\App\Models\BaseModel[]
     */
    public function getAll($where = [], $field = [], $params=[])
    {
        $query = $this->getQueryByModel();
        if (!empty($where)) {
            $query->where($where);
        }
        if (!empty($field)) {
            $query->addSelect($field);
        }

        if (isset($params['sort'])) {
            $query->orderBy(trim($params['sort']), trim(data_get($params, 'order', 'asc')));
        } else {
            $query->orderBy($this->getKeyName(), 'desc');
        }
        $data = $query->get();

        return $data;
    }

    /**
     * 为数组 / JSON 序列化准备日期。
     *
     * @param \DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }


    public function getPerPage()
    {
        return (int)request()->get('pageSize', self::PAGE_SIZE);
    }


    public function modelFilter()
    {
        $filter = str_ireplace('Model', 'ModelFilter',static::class);
        if (!class_exists($filter)) {
            $filter = $this->provideFilter();
        }
        return $filter;
    }


//    public static function getName($id)
//    {
//        if(empty(self::$data)){
//            self::$data = static::query()->select(['id',self::$asname])->pluck( self::$asname,'id')->toArray();
//        }
//        return data_get(self::$data, $id, '');
//    }

    /** 修改toArray后的日期格式 */
//    protected function serializeDate(DateTimeInterface $date)
//    {
//        return $date->format('Y-m-d H:i:s');
//    }
}
